#
# @author Wójcik Karol <wojcikk@student.agh.edu.pl>
# @licence http://www.gnu.org/copyleft/gpl.html GNU/GPL
#

class SubjectsController < ApplicationController
layout 'standard'
before_filter :login_required, :authorize

  def authorize
    if @session['user'].role != "admin"
        redirect_back_or_default :controller => "error", :action => "info"
    end
  end


  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @subject_pages, @subjects = paginate :subjects, :per_page => 10
    sortby = params['sortby']

    case sortby 
    when "name"
	@subjects = Subject.find(:all, :order => "name")
    when "year"
	@subjects = Subject.find(:all, :order => "year")
    when "major"
	@subjects = Subject.find(:all, :order => "major_id")
    when "notes"
	@subjects = Subject.find(:all, :order => "notes")
    else
    end
  end

  def show
    @subject = Subject.find(params[:id])
    @subjects = Subject.find(:all, :order => "name")
  end

  def new
    @Years = [ "1", "2", "3", "4", "5"]
    @subject = Subject.new
    @subjects = Subject.find(:all, :order => "name")
  end

  def create
    @Years = [ "1", "2", "3", "4", "5"]
    @subject = Subject.new(params[:subject])
    @subjects = Subject.find(:all, :order => "name")
    if @subject.save
      flash[:notice] = 'Subject was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @Years = [ "1", "2", "3", "4", "5"]
    @subject = Subject.find(params[:id])
    @subjects = Subject.find(:all, :order => "name")
  end

  def update
    @Years = [ "1", "2", "3", "4", "5"]    
    @subject = Subject.find(params[:id])
    @subjects = Subject.find(:all, :order => "name")
    if @subject.update_attributes(params[:subject])
      flash[:notice] = 'Subject was successfully updated.'
      redirect_to :action => 'show', :id => @subject
    else
      render :action => 'edit'
    end
  end

  def destroy
    @lessons = Lesson.find(:all, :conditions => ["subject_id = ?", params[:id]])
    if @lessons.blank?
      Subject.find(params[:id]).destroy
      redirect_to :action => 'list'
    else
      redirect_to :controller => 'error', :action => 'subject', :code => 'lessons', :id => params[:id]
    end
  end
  
end
